package com.boco.common.converter;

import com.boco.common.entity.Source;
import com.boco.common.entity.data.*;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author pandengke/pdkkpdk@163.com
 * @date 2018/11/14
 */
@Component("facadeProxy")
public class RequestFacadeProxy implements IRequestFacade, ApplicationContextAware {

    private Logger logger = LoggerFactory.getLogger(RequestFacadeProxy.class);

    private ApplicationContext applicationContext;

    @Resource
    HttpServletRequest request;

    @Resource(name = "exampleRequestFacade")
    IRequestFacade exampleRequestFacade;
    @Resource(name = "bocoRequestFacade")
    IRequestFacade bocoRequestFacade;

    private IRequestFacade getRequestFacade() {
        //需要使用哪个医院的接口由登录的参数决定
        String provider = (String) SecurityUtils.getSubject().getSession().getAttribute("hospitalProvider");
        try {
//            getBean由map实现查找,无需优化性能
            return applicationContext.getBean(provider, IRequestFacade.class);
        } catch (Exception ex) {
//            ex.printStackTrace();
            if (provider != null) {
                String msg = "未找到名为" + provider + "的his接口提供者";
                logger.info(msg);
                throw new RuntimeException(msg);
            }
        }
        return bocoRequestFacade;
    }

    @Override
    public Page<Hospital> getHospitals(Map<Object, Object> arguments) {
        return getRequestFacade().getHospitals(arguments);
    }

    @Override
    public Page<Doctor> getDoctors(Map<Object, Object> arguments) {
        return getRequestFacade().getDoctors(arguments);
    }

    @Override
    public Page<Schedule> getSchedules(Map<Object, Object> arguments) {
        return getRequestFacade().getSchedules(arguments);
    }

    @Override
    public Page<Depart> getDeparts(Map<Object, Object> arguments) {
        return getRequestFacade().getDeparts(arguments);
    }

    @Override
    public Page<Source> getSources(Map<Object, Object> arguments) {
        return getRequestFacade().getSources(arguments);
    }

    @Override
    public Page<Appointment> getAppointments(Map<Object, Object> arguments) {
        return getRequestFacade().getAppointments(arguments);
    }

    @Override
    public Map confirm(Map<Object, Object> arguments, String body) {
        return getRequestFacade().confirm(arguments, body);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
